package com.blog.cmrpersonalblog.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.blog.cmrpersonalblog.annotation.RateLimit;
import com.blog.cmrpersonalblog.common.Result;
import com.blog.cmrpersonalblog.dto.auth.request.LoginRequest;
import com.blog.cmrpersonalblog.dto.auth.response.LoginResponse;
import com.blog.cmrpersonalblog.enums.LimitType;
import com.blog.cmrpersonalblog.service.AuthService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 后台管理认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AuthController {

    @Resource
    private AuthService authService;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    @RateLimit(count = 5, time = 60, limitType = LimitType.IP, message = "登录过于频繁，请稍后再试")
    public Result<LoginResponse> login(@RequestBody @Validated LoginRequest loginRequest) {
        log.info("用户登录请求: userName={}", loginRequest.getUserName());
        try {
            LoginResponse response = authService.login(loginRequest);
            log.info("用户登录成功: userId={}, userName={}", response.getUserId(), response.getUserName());
            return Result.success("登录成功", response);
        } catch (Exception e) {
            log.error("用户登录失败: userName={}, error={}", loginRequest.getUserName(), e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 管理员注销
     */
    @PostMapping("/logout")
    public Result<Void> logout() {
        try {
            boolean success = authService.logout();
            if (success) {
                return Result.success("注销成功");
            } else {
                return Result.error("注销失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/userinfo")
    public Result<LoginResponse> getUserInfo() {
        try {
            LoginResponse response = authService.getCurrentUser();
            return Result.success(response);
        } catch (Exception e) {
            return Result.unauthorized(e.getMessage());
        }
    }

    /**
     * 刷新token
     */
    @PostMapping("/refresh")
    public Result<LoginResponse> refreshToken() {
        try {
            LoginResponse response = authService.refreshToken();
            return Result.success("刷新成功", response);
        } catch (Exception e) {
            return Result.unauthorized(e.getMessage());
        }
    }

    /**
     * 检查登录状态
     */
    @GetMapping("/check")
    public Result<Boolean> checkLogin() {
        boolean isLogin = StpUtil.isLogin();
        return Result.success(isLogin);
    }
}
